//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using OpenLS.Spreadsheet.UI.Internals.Resources;
using OpenLS.UI;
using OpenLS.Spreadsheet.UI.Internals;

namespace OpenLS.Spreadsheet.UI
{
    partial class WorkbookResources
    {
        public WorkbookResources()
        {
            InitializeComponent();
        }
        void OnInsertWorksheet(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {
            Workbook wb = SpreadsheetElement.GetWorkbook((DependencyObject)sender);
            if (wb == null)
                return;
            EditionElement.SetEditedCellFor(sender, null);
            EditionElement.SetEditedCellFor(sender, null);
           //// Worksheet ws = wb.InsertWorksheet(wb.Sheets.IndexOf(wb.View.ActiveSheet));
            Worksheet ws = wb.InsertWorksheet(wb.Sheets.Count);
            wb.View.ActiveSheet = ws;
        }
        void OnHideWorksheet(object sender, ExecutedRoutedEventArgs args)
        {
            var worksheet = args.Parameter as Worksheet;
            if (worksheet != null)
            {
                worksheet.IsVisible = false;
                args.Handled = true;
                return;
            }
        }
        void OnMoveToFirst(object sender, ExecutedRoutedEventArgs args)
        {
            var listBox = (ListBox)args.Source;
            if (listBox.Items.Count == 0)
                return;
            listBox.SelectedIndex = 0;
            listBox.ScrollIntoView(listBox.Items[0]);
            args.Handled = true;
        }
        void OnMoveToNext(object sender, ExecutedRoutedEventArgs args)
        {
            var listBox = (ListBox)args.Source;
            if (listBox.Items.Count == 0 || listBox.SelectedIndex == listBox.Items.Count - 1)
                return;
            listBox.SelectedIndex++; //\\increment only visible index
            listBox.ScrollIntoView(listBox.SelectedItem);
            args.Handled = true;
        }
        void OnMoveToPrevious(object sender, ExecutedRoutedEventArgs args)
        {
            var listBox = (ListBox)args.Source;
            if (listBox.Items.Count == 0 || listBox.SelectedIndex == 0)
                return;
            listBox.SelectedIndex--;
            listBox.ScrollIntoView(listBox.SelectedItem);
            args.Handled = true;
        }
        void OnMoveToLast(object sender, ExecutedRoutedEventArgs args)
        {
            var listBox = (ListBox)args.Source;
            if (listBox.Items.Count == 0)
                return;
            listBox.SelectedIndex = listBox.Items.Count - 1;
            listBox.ScrollIntoView(listBox.SelectedItem);
            args.Handled = true;
        }
        void OnMoveToWorksheet(object sender, ExecutedRoutedEventArgs args)
        {
            var worksheet = (Worksheet)args.Parameter;
            worksheet.Workbook.View.ActiveSheet = worksheet;
            args.Handled = true;
        }
        void OnMoveOrCopySheet(object sender, ExecutedRoutedEventArgs args)
        {
            var sheet = (Sheet)args.Parameter;
            if (sheet.Workbook.AreSheetsProtected)
                throw new InvalidOperationException();
            args.Handled = true;
            var moveOrCopySheetControl = new MoveOrCopySheetControl(sheet);
            int oldIndex = sheet.Workbook.Sheets.IndexOf(sheet);
            moveOrCopySheetControl.SelectedIndex = oldIndex;
            WindowServices.ShowDialog(
                moveOrCopySheetControl, UIStringTable.MoveOrCopy,
                                      sender as UIElement,
                delegate
                {
                    int newIndex = moveOrCopySheetControl.SelectedIndex;
                    if (moveOrCopySheetControl.CreateACopy)
                    {
                        var newSheet =
                            new Worksheet(sheet.Workbook,
                                          sheet.Workbook.GetAvailableName(
                                              1, sheet.Name + "({0})"));
                        sheet.Workbook.Sheets.Insert(newIndex, newSheet);
                        if (sheet is Worksheet)
                            newSheet.CopyFrom((Worksheet)sheet,
                                              new PasteInfo(RangeFunctions.ApplyAll, false, false));
                        sheet.Workbook.View.ActiveSheet = newSheet;
                    }
                    else
                    {
                        if (oldIndex == newIndex)
                            return;
                        if (newIndex > oldIndex)
                            newIndex--;
                        sheet.Workbook.Sheets.Move(oldIndex, newIndex);
                    }
                }, o => false);
        }

        void OnMoveTo(object sender, ExecutedRoutedEventArgs args)
        {
            object parameter = args.Parameter;
            if (parameter is Cell)
            {
                MoveTo((Cell)parameter);
                args.Handled = true;
                return;
            }
            var location = (string)args.Parameter;
            string[] ss = location.Split('!');
            string wsName = ss[0];
            if (wsName[0] == '\'')
            {
                wsName = wsName.Substring(1, wsName.Length - 2);
            }
            var workbook = (Workbook)(((FrameworkElement)sender).DataContext);
            Worksheet ws = workbook.GetWorksheet(wsName);
            if (ws == null)
            {
                MessageBox.Show(UIStringTable.ReferenceIsNotValid);
                return;
            }
            //wb.View.ActiveSheet = ws;
            Range r = ws.GetRange(ss[1]);
            if (r == null)
                return;
            // ws.Selection = r;
            //   ws.ActiveCell = r.FirstCell;
            MoveTo(r.FirstCell);
            args.Handled = true;
        }

        static void MoveTo(Cell cell)
        {
            cell.Worksheet.ActiveCell = cell;
            cell.Worksheet.Selection = new SingleCellRange(cell);
            cell.Worksheet.Workbook.View.ActiveSheet = cell.Worksheet;
            cell.Worksheet.IsVisible = true;

        }
        void OnAlways(object sender, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = true;
            args.Handled = true;
        }
        void OnUnhide(object sender, ExecutedRoutedEventArgs args)
        {
            var worksheet = args.Parameter as Worksheet;
            if (worksheet != null)
            {
                var unhideControl = new UnhideControl();
                var hiddenWorksheets = new List<Worksheet>();
                foreach (Worksheet ws in worksheet.Workbook.Sheets)
                    if (!ws.IsVisible)
                        hiddenWorksheets.Add(ws);
                unhideControl.DataContext = hiddenWorksheets;
                unhideControl.Worksheets.SelectedIndex = 0;
                WindowServices.ShowDialog(
                    unhideControl, UIStringTable.Unhide, 
                    sender as UIElement,
                    delegate
                    {
                        var toShow = unhideControl.Worksheets.SelectedItem as Worksheet;
                        if (toShow != null)
                        {
                            toShow.IsVisible = true;
                            toShow.Workbook.View.ActiveSheet = toShow;
                        }
                    }, o => false);
            }
        }
        void OnCanUnhide(object sender, CanExecuteRoutedEventArgs args)
        {
            var worksheet = args.Parameter as Worksheet;
            if (worksheet != null)
            {
                if (worksheet.Workbook.AreSheetsProtected)
                {
                    args.CanExecute = false;
                    args.Handled = true;
                    return;
                }
                foreach (Worksheet ws in worksheet.Workbook.Sheets)
                    if (!ws.IsVisible)
                    {
                        args.Handled = true;
                        args.CanExecute = true;
                    }
            }
        }

        void OnGridPreviewKeyDown(object sender, KeyEventArgs args)
        {
            switch (args.Key)
            {
                case Key.Enter:
                case Key.Escape:
                    break;
                default: return;
            }
            var textBox = args.OriginalSource as TextBox;
            if (textBox == null)
                return;
            var s = textBox.Tag as string;
            if (s != "definedName")
                return;
            var element = (FrameworkElement)Keyboard.FocusedElement;
            if (element == null)
                return;
            element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            element = (FrameworkElement)Keyboard.FocusedElement;
            if (element == null)
                return;
            element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            //\\   args.Handled = true;
        }

        private void OnGridKeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) == 0)
                return;
            switch (e.Key)
            {
                case Key.PageDown:
                    {
                        Workbook workbook = SpreadsheetElement.GetWorkbook((DependencyObject)sender);
                        workbook.View.ActiveSheet = workbook.GetNextVisibleSheet(1);

                        e.Handled = true;
                    }
                    break;
                case Key.PageUp:
                    {
                        Workbook workbook = SpreadsheetElement.GetWorkbook((DependencyObject)sender);
                        workbook.View.ActiveSheet = workbook.GetNextVisibleSheet(-1);
                        e.Handled = true;
                    }
                    break;
            }
        }

        private void OnIsNotProtected(object sender, CanExecuteRoutedEventArgs e)
        {
            Workbook wb = SpreadsheetElement.GetWorkbook((DependencyObject)sender);
            if (wb == null)
                return;
            e.CanExecute = !wb.AreSheetsProtected;
            e.Handled = true;
        }

        private void OnCanHideWorksheet(object sender, CanExecuteRoutedEventArgs e)
        {
            Workbook wb = SpreadsheetElement.GetWorkbook((DependencyObject)sender);
            if (wb == null)
                return;
            e.CanExecute = !wb.AreSheetsProtected;
            if (e.CanExecute)
                e.CanExecute = Enumerable.Count(wb.Sheets, sh => sh.IsVisible) > 1;
            e.Handled = true;
        }

        private void onDeferScrollUpdate(object sender, DragStartedEventArgs e)
        {
            WorksheetViewModel wsvm = SpreadsheetElement.GetWorksheetViewModel((DependencyObject) sender);
            if (wsvm == null)
                return;
            wsvm.DeferScrollUpdate = true;
        }

        private void onDoScrollUpdate(object sender, DragCompletedEventArgs e)
        {
            WorksheetViewModel wsvm = SpreadsheetElement.GetWorksheetViewModel((DependencyObject)sender);
            if (wsvm == null)
                return;
            wsvm.DeferScrollUpdate = false;
        }

        private void OnScrollBarButtonClick(object sender, RoutedEventArgs e)
        {
            ScrollBar sb = (ScrollBar) sender;
            ButtonBase buttonBase = (ButtonBase) e.OriginalSource;
            if (sb.Value < sb.Maximum)
                return;
            Workbook workbook = (Workbook)sb.DataContext;
            Worksheet worksheet = (Worksheet) workbook.View.ActiveSheet;
            if (buttonBase.Command == ScrollBar.LineDownCommand)
            {
                worksheet.ScrollPane.Top++;
            }
            if (buttonBase.Command == ScrollBar.LineRightCommand)
            {
                worksheet.ScrollPane.Left++;
            }

        }
    }
}
